package me.yricky.mayu.ui.fasta_list

import androidx.compose.runtime.mutableStateListOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.yricky.mayu.ui.fasta.FastaSeqModel

/**
 * @author Yricky
 * @date 2022/4/17
 */
class FastaListModel(private val iterator: Iterator<FastaSeqModel> = emptyList<FastaSeqModel>().iterator()) {
    val fastaList:MutableList<FastaSeqModel> = mutableStateListOf()
    private val ioScope = CoroutineScope(Dispatchers.IO)
    val hasMore get() = iterator.hasNext()
    init {
        loadMore()
    }

    private val loadMoreLock = Object()
    fun loadMore(segment:Int = 20){
        if(!hasMore)
            return
        ioScope.launch {
            synchronized(loadMoreLock){
                val segmentList = ArrayList<FastaSeqModel>(segment)
                var num = 0
                while (iterator.hasNext() && num < segment){
                    segmentList.add(iterator.next())
                    num++
                }
                fastaList.addAll(segmentList)
            }
        }
    }
}